package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.properties.AliyunOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliyunOSSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    private final AliyunOssProperties aliyunOssProperties;


    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传，文件名为：{}", file);
        log.info("校验阿里云 {},{}",aliyunOssProperties.getEndpoint(),aliyunOssProperties.getBucketName());
        try {
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
           String url = AliyunOSSUtils.upload(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getBucketName(), file.getBytes(), extName);
            return Result.success(url);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
